<template>
  <div class="app-container">
    <el-card class="card" shadow="hover">
      <div slot="header">
        <p>基本信息</p>
      </div>
      <el-form ref="stepForm" :inline="true" :rules="rules" :model="stepForm">
        <el-form-item label="步骤名称" prop="name">
          <el-input v-model="stepForm.name" type="text" maxlength="20" minlength="3" show-word-limit="">
          </el-input>
        </el-form-item>
        <el-form-item label="关键字类型" prop="step">
          <el-select v-model="stepForm.type">
            <el-option v-for="item in stepOptions" :key="item.index" :label="item.value" :value="item.index" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字">
          <el-select
            v-model="stepInfo.name"
            filterable
            remote
            reserve-step
            :remote-method="getStepsList"
            :loading="stepLoading"
            @change="value => {getStepDetail(value)}"
          >
            <el-option v-for="item in stepList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="card">
      <div slot="header">
        <p>参数信息</p>
      </div>
      <el-table v-loading="loading" border :data="paramsList">
        <el-table-column label="参数名" prop="name" />
        <el-table-column label="类型" prop="type" />
        <el-table-column label="参数值" prop="value">
          <template slot-scope="scope">
            <el-input v-model="scope.row.value" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleParamsBound(scope.$index)">绑定参数</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="card">
      <div slot="header">
        <p>返回信息</p>
      </div>
      <el-table :data="returnList" border>
        <el-table-column label="参数名" prop="name" />
        <el-table-column label="类型" prop="type" />
        <el-table-column label="路径" prop="path" />
        <el-table-column label="参数说明" prop="detail" />
      </el-table>
    </el-card>
    <!-- 预期判断 -->
    <el-card class="card">
      <div slot="header">
        <p>预期值校验</p>
      </div>
      <el-button type="primary" size="small" @click="addExpect">增加预期值</el-button>
      <el-table :data="expectList" border="">
        <el-table-column label="类型" prop="type">
          <template slot-scope="scope">
            <el-select v-model="scope.row.type">
              <el-option v-for="item in expectType" :key="item.index" :label="item.value" :value="item.index"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="预期值名称" prop="name">
          <template slot-scope="scope">
            <el-input v-if="scope.row.type !== 'code'" v-model="scope.row.name"/>
          </template>
        </el-table-column>
        <el-table-column label="路径" prop="path">
          <template slot-scope="scope">
            <el-input v-if="scope.row.type !== 'code'" v-model="scope.row.path"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="预期值" prop="value">
          <template slot-scope="scope">
            <el-input v-if="scope.row.type !== 'code'" v-model="scope.row.value"></el-input>
            <el-select v-else v-model="scope.row.value" @change="checkExpectValid">
              <el-option v-for="item in statusCode" :key="item.index" :label="item.value" :value="item.index"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="small" @click="deleteExpect(scope.$index, expectList)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--boundParams dialog-->
    <el-dialog :visible.sync="paramsDialogVisible" title="绑定参数">
      <el-table :data="boundParamsList" highlight-current-row @current-change="handleCurrentRow">
        <el-table-column label="顺序" prop="step_num" />
        <el-table-column label="步骤名称" prop="step_name" />
        <el-table-column label="类型" prop="type" />
        <el-table-column label="参数名" prop="name" />
        <el-table-column label="参数说明" prop="detail" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="paramsBound">确定</el-button>
        <el-button type="danger" size="small" style="float: right; margin-left: 30px" @click="paramsDialogVisible=false">取消</el-button>
      </span>
    </el-dialog>
    <div class="el-button-group" style="margin-top: 20px">
      <el-button type="primary" size="medium" style="float: right" @click="isEdit ?updateDate():createData()">确定</el-button>
      <el-button type="normal" style="margin-right: 30px" size="medium" @click="$router.back(-1)">返回</el-button>
    </div>
  </div>
</template>

<script>
const defaultForm = {
  id: undefined,
  name: '',
  case: undefined,
  type: 'interface',
  step_info: '',
  params: '',
  expect: '',
  return_values: '',
  remark: ''
}
import { getStep, getPreSteps, createStep, updateStep } from '@/api/step'
import { getInterface, getInterfaceList } from '@/api/interface'
import { getDataBaseList, getDataBase } from '@/api/dataBase'
import { collectList } from './index'
import { expectType, stepOptions, statusCode } from '../config'
export default {
  name: 'StepDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      stepForm: Object.assign({}, defaultForm),
      tempRoute: {},
      paramsList: [],
      returnList: [],
      loading: false,
      caseId: undefined,
      stepLoading: false,
      stepList: [],
      stepInfo: {
        name: ''
      },
      boundParamsList: [],
      list: [],
      rules: {
        name: [
          { required: true, message: '接口名称不能为空', trigger: 'change' },
          { min: 3, max: 30, message: '长度限制为3-30' }
        ]
      },
      stepType: 'interface',
      stepOptions: stepOptions,
      paramsDialogVisible: false,
      currentRow: null,
      currentIndex: undefined,
      expectList: [],
      expectType: expectType,
      statusCode: statusCode
    }
  },
  created() {
    this.caseId = this.$route.params && this.$route.params.id
    if (this.isEdit) {
      console.log(this.$route.params)
      this.fetchDate(this.caseId)
    } else {
      console.log('stepForm:', this.stepForm)
      this.tempRoute = Object.assign({}, this.$route)
    }
  },
  methods: {
    fetchDate(id) {
      getStep(id).then((response) => {
        this.stepForm = response.data
        this.stepInfo = JSON.parse(this.stepForm.step_info)
        this.paramsList = JSON.parse(this.stepForm.params)
        this.returnList = JSON.parse(this.stepForm.return_values)
        this.expectList = JSON.parse(this.stepForm.expect)
      })
    },
    collectStepForm() {
      this.stepForm.params = JSON.stringify(this.paramsList)
      this.stepForm.return_values = JSON.stringify(this.returnList)
      if (typeof this.stepInfo.name === Number) {
        this.stepInfo.name = this.stepList.filter(item => {
          return item.id === this.stepInfo.name
        })[0].name
      }
      this.stepForm.step_info = JSON.stringify(this.stepInfo)
      this.stepForm.expect = JSON.stringify(this.expectList)
    },
    createData() {
      if (this.checkExpectValid()) {
        this.collectStepForm()
        this.stepForm.case = this.caseId
        this.$refs.stepForm.validate(valid => {
          if (valid) {
            createStep(this.stepForm).then((response) => {
              if (response) {
                console.log('创建step成功')
                this.$router.go(-1)
              }
            })
          }
        })
      } else {
        this.$message.error('状态码校验只能有一个')
      }
    },
    updateDate() {
      if (this.checkExpectValid()) {
        this.collectStepForm()
        this.$refs.stepForm.validate(valid => {
          if (valid) {
            updateStep(this.caseId, this.stepForm).then(() => {
              this.$notify({
                title: '提示',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.$router.go(-1)
            })
          }
        })
      } else {
        this.$message.error('状态码校验只能有一个且字段不能为空')
      }
    },
    nullValid(attr) {
      return attr !== null && attr !== undefined && attr !== ''
    },
    checkExpectValid() {
      let count = 0
      this.expectList.filter(item => {
        if (item.type === 'code') {
          count = count + 1
        } else if (item.type === 'header' || item.type === 'body') {
          const v = this.nullValid(item.name) && this.nullValid(item.path) && this.nullValid(item.value)
          if (!v) {
            count = count + 1
          }
        }
      })
      return count <= 1
    },
    addExpect() {
      const expectItem = {
        type: 'header',
        name: '',
        path: '$response',
        value: ''
      }
      this.expectList.push(expectItem)
    },
    deleteExpect(index, rows) {
      rows.splice(index, 1)
    },
    handleParamsBound(index) {
      console.log('index:', index)
      this.currentIndex = index
      this.boundParamsList = []
      this.getPreStep()
      this.paramsDialogVisible = true
    },
    paramsBound() {
      console.log('this.current:', this.currentRow)
      if (this.currentRow) {
        this.paramsList[this.currentIndex].value = `${this.currentRow.step_name}_${this.currentRow.step_num}_${this.currentRow.name}`
        this.paramsDialogVisible = false
      } else {
        this.$notify({
          title: '提示信息',
          message: '请至少选择一个参数',
          type: 'warning'
        })
      }
    },
    handleCurrentRow(row) {
      this.currentRow = row
    },
    collectBoundParams(dataList) {
      // debugger
      console.log('dataList:', dataList)
      if (dataList.length > 0) {
        dataList.forEach(item => {
          const returnList = JSON.parse(item.return_values)
          console.log(returnList)
          returnList.forEach(rItem => {
            const boundParamsItem = {
              step_num: item.step_num,
              step_name: item.name,
              type: rItem.type,
              name: rItem.name,
              detail: rItem.detail
            }
            this.boundParamsList.push(boundParamsItem)
          })
        })
      }
      console.log('this.boundParamsList:', this.boundParamsList)
    },
    getPreStep() {
      const params = {
        case: this.isEdit ? this.stepForm.case : this.caseId,
        page: 1,
        limit: 20
      }
      if (this.isEdit) {
        params.step = this.stepForm.step_num
      }
      getPreSteps(params).then(response => {
        console.log('response:', response)
        this.collectBoundParams(response.results)
      })
    },
    getStepsList(query) {
      if (query !== undefined) {
        this.stepLoading = true
        const params = {
          search: query
        }
        switch (this.stepForm.type) {
          case 'web':
            break

          case 'interface':
            getInterfaceList(params).then((response) => {
              this.stepList = response.results
              this.stepLoading = false
            })
            break
          case 'sql':
            getDataBaseList(params).then((response) => {
              this.stepList = response.results
              console.log('interfaceList: ', this.stepList)
              this.stepLoading = false
            })
            break
        }
      }
    },
    getStepDetail(value) {
      switch (this.stepForm.type) {
        case 'interface':
          getInterface(value).then(response => {
            const data = response.data
            this.paramsList = []
            this.returnList = []
            collectList(data.headers, this.paramsList, 'headers')
            collectList(data.params, this.paramsList, 'params')
            collectList(data.response_headers, this.returnList, 'response_headers')
            collectList(data.response_params, this.returnList, 'response_params')
            // this.expectList = JSON.parse(data.expect)
            this.stepInfo.name = data.name
            this.stepInfo.method = data.method
            this.stepInfo.url = data.url
          })
          break
        case 'sql':
          getDataBase(value).then(response => {
            this.paramsList = JSON.parse(response.data.params)
          })
          break
      }
    }
  }
}
</script>

<style scoped>
.card {
  margin-top: 50px;
}
</style>
